/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * 后序递归，通过赋值节点值===2判断是否是公共祖先节点
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (root, p, q) {
    return lowestLevel(root, p, q)
};


function lowestLevel(root, p, q) {
    if (root === null) return 0

    let l = lowestLevel(root.left, p, q),
        r = lowestLevel(root.right, p, q),
        flag = 0;
    
    if(l instanceof TreeNode){
        return l
    }
    if(r instanceof TreeNode){
        return r
    }

    if (root == p || root == q) {
        flag = 1
    }

    if (l + r + flag === 2) {
        return root
    }

    return l + r + flag
}